package com.bauer.java.hadoop.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @Author ：rui.wei
 * @Date ：Created in 14:58 2019/8/13
 * @Description：
 */
public class ConsumerClient {

    private KafkaConsumer<String, String> consumer = null;
    private String topicName = null;
    private int numThreads = 0;

    public ConsumerClient(String groupId, boolean largest, String topicName, int numThreads) {
        this.topicName = topicName;
        this.numThreads = numThreads;

        // 1. 给定Consumer连接的相关参数
        Properties props = new Properties();
        // a. 给定group id
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "99.48.58.219:9092,99.48.58.222:9092");
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        // 2. 创建Consumer上下文
        ConsumerConfig config = new ConsumerConfig(props);
        // 3. 创建Consumer连接器
        consumer = new KafkaConsumer<String, String>(props);

        consumer.subscribe(Arrays.asList(topicName));
    }

    public void shutdown() {
        if (this.consumer != null) {
            // 当调用shutdown后，KafkaStream所产生的ConsumerIterator迭代器就没有数据了
            this.consumer.close();
        }
    }

    public void run() {
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ZERO);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        String groupId = "170505_2";
        boolean largest = true;
        String topicName = "test";
        int numThreads = 1;
        ConsumerClient demo = new ConsumerClient(groupId, largest, topicName, numThreads);
        demo.run();

        // 休息一段数据后关闭
        Thread.sleep(20000);

        demo.shutdown();
    }


}
